package cn.bdqn.service.impl;

import cn.bdqn.config.shiro.MyRealm;
import cn.bdqn.mapper.RoleMapper;
import cn.bdqn.pojo.Role;
import cn.bdqn.pojo.SysRoleRight;
import cn.bdqn.service.RoleService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.RealmSecurityManager;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    RoleMapper roleMapper;
    @Resource
   SysRoleRightServiceImpl sysRoleRightService;

    @Override
    public List<Role> findAllRoles() {
        List<Role> lsit = roleMapper.selectList(null);
        return lsit;
    }

    @Override
    public IPage<Role> selectList(Integer pageNo, Integer pageSize, String roleName) {
        Page page=new Page(pageNo,pageSize);
        IPage iPage = roleMapper.selectLists(page, roleName);
        return iPage;
    }

    @Override
    public void insert(Role role,String[] rightCodes) {
        roleMapper.insert(role);
        if (rightCodes!=null&&rightCodes.length>0){
            for (String rightCode : rightCodes) {
                SysRoleRight roleRight=new SysRoleRight();
                roleRight.setRfRoleId(role.getRoleId());
                roleRight.setRfRightCode(rightCode);
                sysRoleRightService.addSysRoleRight(roleRight);
            }

        }
    }

    @Override
    public Role selectOne(Long roleId) {
        Role role = roleMapper.selectById(roleId);
        return role;
    }

    @Override
    public void update(Role role, String[] rightCodes) {
        //修改
        roleMapper.updateById(role);
        sysRoleRightService.deleteSysRoleRightByRoleId(role.getRoleId());
        //再添加进
        if (rightCodes != null && rightCodes.length > 0) {
            for (String rightCode : rightCodes) {
                SysRoleRight roleRight = new SysRoleRight();
                roleRight.setRfRoleId(role.getRoleId());
                roleRight.setRfRightCode(rightCode);
                sysRoleRightService.addSysRoleRight(roleRight);
            }

        }
        //清空所有权限缓存
        RealmSecurityManager realmSecurityManager = (RealmSecurityManager) SecurityUtils.getSecurityManager();
        MyRealm next = (MyRealm)realmSecurityManager.getRealms().iterator().next();
        next.clearAllCachedAuthorizationInfo();
    }


    @Override
    public void delete(Long id) {
        //先删除权限
        sysRoleRightService.deleteSysRoleRightByRoleId(id);
        //再删除角色 主表
       roleMapper.deleteById(id);
    }

    @Override
    public Role selectByUserId(Long userId) {
        return roleMapper.selectByUserId(userId);
    }

}
